package com.xgimi.open.skill.datamanager.web.component;

import com.alibaba.fastjson.JSON;

import com.xgimi.commons.base.Result;
import com.xgimi.commons.exception.CommonCode;
import org.springframework.boot.actuate.health.Health;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author coderzpw.zhang
 * @version 1.0
 * @description 返回统一数据结构
 * @date 2023/2/3 15:02
 */
@ControllerAdvice
public class CommonResultResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 若是健康检查的结果，则直接返回
        if (body instanceof Health) {
            return body;
        }
        // 如果直接响应字符串返回,则会报类型转换异常.
        if (body instanceof String) {
            return JSON.toJSONString(new Result(body.toString()));
        }
        // 如果已经是Result类型， 就没必要再包装一层了
        if (body instanceof Result) {
            return body;
        }

        if (methodParameter.getMethod().getName() == "error") {
            return new Result<String>(CommonCode.SYS_ERROR.getCode(), body.toString());
        }
        return new Result(body);
    }
}
